import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


@SuppressWarnings("serial")
public class FrameAdicionaCliente extends JFrame {
	
	private FramePrincipal fp ;
	
	private PreparedStatement pst ;
	private ResultSet rs ;
	
	private JPanel painel  ;
	private JTextField fieldNome  ;
	private JTextField fieldTelefone  ;
	
	public FrameAdicionaCliente(FramePrincipal framep) {
		fp = framep ;
		
		setSize(800/3,600/3) ;
		setResizable(false);
		setLocationRelativeTo(fp);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setTitle("Novo cliente");
		
		painel = new JPanel() ;	
		getContentPane().add(painel) ;
		painel.setLayout(null);
		
		fieldNome = new JTextField();
		fieldNome.setBounds(10, 36, 226, 20);
		painel.add(fieldNome);
		fieldNome.setColumns(10);
		
		fieldTelefone = new JTextField();
		fieldTelefone.setBounds(10, 85, 226, 20);
		painel.add(fieldTelefone);
		fieldTelefone.setColumns(10);
		
		JLabel labelUsuario = new JLabel("Nome");
		labelUsuario.setBounds(10, 22, 46, 14);
		painel.add(labelUsuario);
		
		JLabel labelSenha = new JLabel("Telefone");
		labelSenha.setBounds(10, 72, 105, 14);
		painel.add(labelSenha);
		
		JButton botaoOk = new JButton("OK");
		botaoOk.setBounds(145, 127, 89, 23);
		painel.add(botaoOk);
		botaoOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String n, temp ;
				int t ;
				n = fieldNome.getText().trim();
				if (!n.equals("")) {
					try {
						temp = fieldTelefone.getText().trim();
						t = Integer.parseInt(temp);
						pst = fp.conn.prepareStatement("INSERT INTO Cliente VALUES (null,?,?,0,0)");
						pst.setString(1, n);
						pst.setInt(2, t);
						pst.execute();
						pst = fp.conn.prepareStatement("SELECT * FROM Cliente WHERE id=(SELECT MAX(id) FROM Cliente)");
						rs = pst.executeQuery();
						if (rs.next()) fp.clienteModel.clientes.add(new Cliente(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getInt(5)) );
						pst.close();
						fp.clienteModel.fireTableRowsInserted(fp.clienteModel.clientes.size()-1, fp.clienteModel.clientes.size()-1);
						dispose();
					} catch (Exception ex) {
						JOptionPane.showMessageDialog(null,"Digite um valor valido no campo telefone") ;
					}
				} else JOptionPane.showMessageDialog(null, "Digite um valor valido no campo nome"); 				
			}
		});	
		
		setVisible(true);
	}
	

}
